const bcrypt = require("bcrypt");
const userModel = require("../models/userModel");

const jwt = require("jsonwebtoken");

// 登录成功回调
// 这里可以根据实际需求进行调整，比如返回用户信息、生成token等
const loginSuccessCallback = (res, user) => {
  console.log("用户登录成功:", user);
  // const token = jwt.sign(user, process.env.JWT_SECRET, {
  //   expiresIn: "1h",
  // });
  const token = jwt.sign(
    {
      exp: Math.floor(Date.now() / 1000) + 60 * 60 * 24, // 过期时间为24小时
      userId: user.id,
      email: user.email,
    },
    process.env.JWT_SECRET
  );
  res.status(200).json({
    code: 0,
    msg: "登录成功",
    data: {
      userInfo: {
        userId: user.id,
        username: user.username,
        email: user.email,
      },
      token: token,
    },
  });
};

// 创建用户
const createUser = async (req, res) => {
  const { username, email, password } = req.body;

  const hashedPassword = await bcrypt.hash(password, 10);

  try {
    const result = await userModel.createUser(username, email, hashedPassword);
    res
      .status(200)
      .json({ code: 0, msg: "用户创建成功", userId: result.insertId });
  } catch (error) {
    console.error("❌ 创建用户失败:", error);
    res.status(500).json({ code: 500, msg: "创建用户失败" });
  }
};

// 用户登录
const loginUser = async (req, res) => {
  const { email, password } = req.body;

  try {
    const user = await userModel.findUser(email);

    if (!user.length) {
      return res.status(200).json({ code: 500, msg: "用户不存在" });
    }

    const originalPassword = user[0].password;

    const isPasswordValid = await bcrypt.compare(password, originalPassword);

    if (!isPasswordValid) {
      return res.status(200).json({ code: 500, msg: "密码错误" });
    }

    // return res.status(200).json({ code: 0, msg: "登录成功", data: user[0] });
    loginSuccessCallback(res, user[0]);
  } catch (error) {
    console.error("❌ 登录失败:", error);
    return res.status(500).json({ code: 500, msg: "登录失败" });
  }
};

// 修改用户信息
const updateUserInfo = async (req, res) => {
  // 都是非必填的参数
  const { username, birthdate, bio, sex } = req.body;
  try {
    const result = await userModel.updateUserInfo(
      { username, birthdate, bio, sex },
      req.user.userId
    );
    console.log("更新用户信息结果:", result);
    if (result.affectedRows > 0) {
      userModel.findUser(req.user.email).then((user) => {
        // 更新成功后返回最新的用户信息
        return res.status(200).json({
          code: 0,
          msg: "用户名更新成功",
          data: {
            userId: user[0].userId,
            username: user[0].username,
            email: user[0].email,
            birthdate: user[0].birthdate,
            bio: user[0].bio,
            avatar: user[0].avatar, // 假设用户模型中有头像字段
            sex: user[0].sex,
          },
        });
      });
    } else {
      return res.status(200).json({ code: 0, msg: "用户未找到" });
    }
  } catch (error) {
    console.error("❌ 更新用户名失败:", error);
    return res.status(500).json({ code: 500, msg: "更新用户名失败" });
  }
};

// 获取用户信息
const getUserInfo = async (req, res) => {
  try {
    const user = await userModel.findUserById(req.user.userId);
    if (user) {
      return res.status(200).json({
        code: 0,
        msg: "获取用户信息成功",
        data: user,
      });
    } else {
      return res.status(200).json({ code: 500, msg: "用户未找到" });
    }
  } catch (error) {
    console.error("❌ 获取用户信息失败:", error);
    return res.status(500).json({ code: 500, msg: "获取用户信息失败" });
  }
};

// 上传头像
const uploadAvatar = async (req, res) => {
  try {
    console.log("上传的文件信息:", req.file);
    const userId = req.user.userId;
    const avatarPath = "/uploads/avatar/" + req.file.filename; // 获取上传的文件路径

    // 更新用户头像路径到数据库
    const result = await userModel.updateUserInfo(
      { avatar: avatarPath },
      userId
    );
    if (result.affectedRows > 0) {
      // 返回更新后的用户信息
      const user = await userModel.findUserById(userId);
      return res.status(200).json({
        code: 0,
        msg: "头像上传成功",
        data: {
          id: user.userId,
          username: user.username,
          email: user.email,
          birthdate: user.birthdate,
          bio: user.bio,
          avatar: user.avatar, // 返回
          sex: user.sex,
        },
      });
    } else {
      return res.status(200).json({
        code: 500,
        msg: "头像上传失败",
      });
    }
  } catch (error) {
    console.error("❌ 头像上传失败:", error);
    return res.status(500).json({ code: 500, msg: "头像上传失败" });
  }
};

module.exports = {
  createUser,
  loginUser,
  updateUserInfo,
  getUserInfo,
  uploadAvatar,
};
